<template>
	<view class="page-main">
		<view class="turntable">
			<LuckyWheel ref="myLucky" width="600rpx" height="600rpx" :default-style="wheelStyle" :blocks="blocks"
				:prizes="prizes" :buttons="buttons" @start="startCallBack" @end="endCallBack" />
		</view>

		<view class="collapse">
			<view class="collapse-title-box">
				<view class="collapse-title">
					<u--text text="菜单标签" size="30rpx" />
					<u-icon name="question-circle" size="36rpx" />
				</view>
				<view class="collapse-edit">
					<u--text v-if="menuEditStatus===''" type="primary" text="编辑" size="30rpx"
						@click="onOpenActionSheet()" />
					<u--text v-else type="primary" text="取消" size="30rpx" @click="onOpenActionSheet(false)" />
				</view>
			</view>

			<scroll-view style="height:calc(100vh - 60rpx - 600rpx - 20px - 100rpx)" scroll-y>
				<my-collapse ref="myCollapse" accordion>
					<my-collapse-item v-for="(menuItem,menuIndex) in foodMenuList" :key="menuIndex"
						:title="menuItem.name" :disabledArrow="menuEditStatus===''">
						<view>
							<view class="menu-tag" v-for="(item,index) in menuItem.foodList" :key="index">
								<u-tag v-if="item.selected" :text="item.name" plain plainFill
									:closable="menuEditStatus==='edit'" size="medium" @click="tagClick(item)"
									@close="tagClose(item,index,menuIndex)" color="#53c21d" borderColor="#53c21d" />
								<u-tag v-else :text="item.name" plain :closable="menuEditStatus==='edit'" size="medium"
									@click="tagClick(item)" @close="tagClose(item,index,menuIndex)" color="#82848a"
									borderColor="#82848a" />
							</view>
							<view class="menu-tag" v-if="menuEditStatus===''">
								<u-button plain icon="plus" size="small" customStyle="min-width:auto;"
									@click="onAddTag(menuItem.id,menuIndex)" />
							</view>
						</view>
						<template :slot="menuEditStatus!==''?'right-icon':''">
							<u-icon name="edit-pen" size="36rpx"
								@tap.native.stop="onEditClassifyMenu(menuItem,menuIndex)"
								v-if="menuEditStatus==='edit'" />
							<u-icon name="list" size="36rpx"
								@tap.native.stop="onSortClassifyMenu(menuItem,menuIndex)"
								v-else-if="menuEditStatus==='sort'" />
							<u-icon name="share-square" size="36rpx"
								@tap.native.stop="onShareClassifyMenu(menuItem,menuIndex)"
								v-else-if="menuEditStatus==='share'" />
							<u-icon name="trash" size="36rpx"
								@tap.native.stop="onDeleteClassifyMenu(menuItem,menuIndex)"
								v-else-if="menuEditStatus==='del'" />
						</template>
					</my-collapse-item>
					<u-loading-icon :show="showLoading" size="45" color="#505050" />
				</my-collapse>
			</scroll-view>

		</view>

		<u-modal :show="showAddTag" title="提示" showCancelButton @cancel="onAddCancel" @confirm="onAddConfirm">
			<u--form labelWidth="auto">
				<u-form-item :label="`${tagForm.title}：`" borderBottom required>
					<u--input v-model="tagForm.content" placeholder="请输入内容" border="none" clearable
						customStyle="width: 350rpx;" />
				</u-form-item>
			</u--form>
		</u-modal>

		<u-action-sheet :actions="actionSheet" :show="showActionSheet" cancelText="取消" @close="onAddCancel"
			@select="onActionSelect" closeOnClickOverlay safeAreaInsetBottom :closeOnClickAction="false" />
	</view>
</template>

<script>
	import LuckyWheel from '@/components/@lucky-canvas/uni/lucky-wheel' // 大转盘
	import MyCollapse from '@/components/my-collapse/my-collapse' // 折叠面板
	import MyCollapseItem from '@/components/my-collapse/my-collapse-item' // 折叠面板
	// import DragSortItem from '@/components/myCustom/drag-sort-item' // 拖拽排序

	export default {
		components: {
			LuckyWheel,
			MyCollapse,
			MyCollapseItem
		},
		data() {
			return {
				firstOpen: true,
				showLoading: true,
				showAddTag: false,
				tagForm: {
					title: null,
					menuIndex: null,
					content: null,
					classifyId: null,
					isEdit: false
				},
				foodMenuList: [],
				menuEditStatus: '',
				wheelStyle: {
					fontSize: '28rpx'
				},
				blocks: [{
					padding: '20rpx',
					background: '#ffaa7f'
				}],
				prizes: [],
				buttons: [{
					radius: '90rpx',
					background: '#ffffff',
				}, {
					radius: '80rpx',
					background: '#ffaa7f',
					pointer: true,
					fonts: [{
						text: '今天\n吃什么',
						top: '-40rpx',
						fontSize: '36rpx'
					}]
				}, ],
				showActionSheet: false,
				actionSheet: [{
					name: '新增',
					value: 'add'
				}, {
					name: '修改',
					value: 'edit'
				}, {
					name: '排序',
					value: 'sort'
				}, {
					name: '分享',
					value: 'share'
				}, {
					name: '删除',
					value: 'del'
				}, ],
			}
		},
		onLoad() {
			const menuData = uni.getStorageSync('turntable_menu_data');

			let count = 0
			outerLoop: for (let i = 0; i < menuData.length; i++) {
				let itemArr = menuData[i].foodList
				for (let j = 0; j < itemArr.length; j++) {
					let item = itemArr[j]
					if (item.selected) {
						this.prizes.push({
							id: item.classifyId + '-' + item.id,
							range: 10,
							background: `rgb(${uni.$u.random(150, 255)}, ${uni.$u.random(150, 255)}, ${uni.$u.random(150, 255)})`,
							fonts: [{
								text: item.name
							}],
						});

						if (++count >= 20) {
							break outerLoop;
						}
					}
				}
			}

			if (menuData && menuData != {}) {
				this.foodMenuList = menuData
			} else {
				this.foodMenuList = require('@/common/menuData.js').default
				uni.setStorageSync('turntable_menu_data', this.foodMenuList);

			}

			this.showLoading = false
		},

		onShow() {
			if (!this.firstOpen) {
				this.$refs.myLucky.init();
			}
		},
		onReady() {
			this.firstOpen = false
		},
		onHide() {
			uni.setStorage({
				key: 'turntable_menu_data',
				data: this.foodMenuList
			});
			this.hideMyLucky()
			this.menuEditStatus = ''
		},
		onShareAppMessage(res) {
			return {
				title: '甜蜜小屋',
				desc: '快来记录你们的甜蜜瞬间',
				path: '/pages/index/index'
			}
		},
		onShareTimeline(res) {
			return {
				title: '快来记录你们的甜蜜瞬间',
				path: '/pages/index/index'
			}
		},
		methods: {
			tagClick(item) {
				if (this.prizes.length >= 20) {
					uni.$u.toast('已到最大数');
					return
				}
				item.selected = !item.selected
				let index = this.prizes.findIndex(e => e.id === (item.classifyId + '-' + item.id));
				if (item.selected && index == -1) {
					this.prizes.push({
						id: item.classifyId + '-' + item.id,
						range: 10,
						background: `rgb(${uni.$u.random(150, 255)}, ${uni.$u.random(150, 255)}, ${uni.$u.random(150, 255)})`,
						fonts: [{
							text: item.name,
						}],
					});
				} else if (index > -1) {
					this.prizes.splice(index, 1);
				}

			},
			tagClose(item, index, menuIndex) {
				this.foodMenuList[menuIndex].foodList.splice(index, 1);
				this.resizeCollapse()
				if (item.selected) {
					let prizesIndex = this.prizes.findIndex(e => e.id === (item.classifyId + '-' + item.id))
					if (prizesIndex > -1) {
						this.prizes.splice(prizesIndex, 1);
					}
				}

			},
			onAddClassify() {
				this.hideMyLucky()
				this.tagForm.isEdit = false;
				this.tagForm.title = '分类名';
				this.tagForm.content = null;
				this.showAddTag = true
			},
			onAddTag(classifyId, menuIndex) {
				this.hideMyLucky()
				this.tagForm.title = '标签名';
				this.tagForm.content = null;
				this.tagForm.menuIndex = menuIndex;
				this.tagForm.classifyId = classifyId;
				this.showAddTag = true
			},
			onAddCancel() {
				this.showActionSheet = false;
				this.showAddTag = false;
				this.initMyLucky();
			},
			onAddConfirm() {
				let tagForm = this.tagForm
				if (!tagForm.content) {
					uni.$u.toast('不能为空');
					return
				}

				this.showAddTag = false;

				if (tagForm.title === '分类名') {
					//修改分类名
					if (tagForm.isEdit) {
						this.foodMenuList[tagForm.menuIndex].name = tagForm.content
						uni.$u.toast('修改成功');
						this.initMyLucky();
						return;
					}
					//添加分类
					this.foodMenuList.push({
						id: (this.foodMenuList.length || 0) + 1,
						name: tagForm.content,
						foodList: []
					});
					uni.$u.toast('添加成功');
					this.initMyLucky();
					return;
				}

				//添加标签
				let foodMenuItem = this.foodMenuList[tagForm.menuIndex];
				foodMenuItem.foodList.push({
					id: (foodMenuItem.foodList.length || 0) + 1,
					classifyId: foodMenuItem.id,
					name: tagForm.content,
					selected: false
				});
				this.resizeCollapse()
				uni.$u.toast('添加成功');
				this.initMyLucky();

			},
			onActionSelect(e) {
				this.showActionSheet = false
				switch (e.value) {
					case 'add':
						this.showAddTag = true
						this.tagForm.title = '分类名';
						this.tagForm.content = null;
						this.tagForm.menuIndex = null;
						this.tagForm.classifyId = null;
						break;
					default:
						this.menuEditStatus = e.value
						this.initMyLucky();
						break;
				}
			},
			onOpenActionSheet(isEdit = true) {
				if (isEdit) {
					this.hideMyLucky()
					this.showActionSheet = true
				} else {
					this.resizeCollapse();
					this.menuEditStatus = ''
				}
			},
			/**
			 * 分类菜单 - 修改
			 * @param {Object} menuItem
			 * @param {Object} menuIndex
			 */
			onEditClassifyMenu(menuItem, menuIndex) {
				this.hideMyLucky()
				this.showAddTag = true
				this.tagForm.isEdit = true;
				this.tagForm.title = '分类名';
				this.tagForm.content = menuItem.name;
				this.tagForm.menuIndex = menuIndex;
				this.tagForm.classifyId = menuItem.id;
			},
			/**
			 * 分类菜单 - 删除
			 * @param {Object} menuItem
			 * @param {Object} menuIndex
			 */
			onDeleteClassifyMenu(menuItem, menuIndex) {
				uni.showModal({
					title: "提示",
					content: `确定要删除 “${menuItem.name}” 分类吗？`,
					success: (res) => {
						if (res.confirm) {
							this.foodMenuList.splice(menuIndex, 1)
							uni.$u.toast('删除成功');
						}
						this.initMyLucky();
					}
				});
			},
			/**
			 * 分类菜单 - 排序
			 * @param {Object} menuItem
			 * @param {Object} menuIndex
			 */
			onSortClassifyMenu(menuItem, menuIndex) {
				console.log("aaaaaaaaaaaaaaaa");
			},
			/**
			 * 分类菜单 - 分享
			 * @param {Object} menuItem
			 * @param {Object} menuIndex
			 */
			onShareClassifyMenu(menuItem, menuIndex) {
				console.log("aaaaaaaaaaaaaaaa");
			},

			/**
			 * 调整折叠面板的宽度
			 */
			resizeCollapse() {
				this.$nextTick(() => {
					this.$refs.myCollapse.init();
				})
			},
			/**
			 * 初始化转盘
			 */
			initMyLucky() {
				setTimeout(() => {
					this.$refs.myLucky.init();
				}, 300)
			},
			/**
			 * 隐藏转盘
			 */
			hideMyLucky() {
				this.$refs.myLucky.hideCanvas();
			},
			/**
			 * 点击抽奖按钮触发回调
			 */
			startCallBack() {
				if (this.prizes.length < 2) {
					uni.$u.toast('至少需要2个标签');
					return
				}
				// 先开始旋转
				this.$refs.myLucky.play()
				// 使用定时器来模拟请求接口
				setTimeout(() => {
					// 调用stop停止旋转并传递中奖索引
					this.$refs.myLucky.stop()
				}, 3000)
			},
			/**
			 * 抽奖结束触发回调
			 * @param {Object} prize
			 */
			endCallBack(prize) {
				// 奖品详情
				uni.showModal({
					title: "提示",
					content: "今天奖励自己：" + prize.fonts[0].text,
					showCancel: false
				});
			}
		}
	}
</script>

<style>
	.turntable {
		margin-bottom: 20px;
	}

	.collapse {
		font-size: 20px;
	}

	.collapse-title-box {
		border-radius: 10px 10px 0 0;
		background-color: rgba(255, 255, 255, 0.8);
		height: 100rpx;
		line-height: 100rpx;
		padding: 0 15px;
	}

	.collapse-title {
		display: inline-flex;
	}

	.collapse-edit {
		float: right;
	}

	.u-collapse {
		border-radius: 0 0 10px 10px;
		background-color: rgba(255, 255, 255, 0.8);
	}

	.u-cell--clickable {
		background-color: transparent !important;
	}

	.menu-tag {
		display: inline-block;
		margin-right: 16rpx;
		margin-bottom: 16rpx;
	}
</style>